package com.lmj.service;

import com.alibaba.fastjson.JSON;
import com.lmj.pojo.Content;
import com.lmj.utils.Contant;
import com.lmj.utils.HtmlParseUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 业务编写
 */

@Service
public class ContentService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    // 1、解析数据放入到es索引中
    public Boolean parseContent(String keyWords) throws IOException {
        List<Content> contents = HtmlParseUtils.parseJd(keyWords);
        // 把查询的数据批量插入到索引库中
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");
        for (int i = 0; i < contents.size(); i++) {
            bulkRequest.add(new IndexRequest(Contant.JD_INDEX).source(JSON.toJSONString(contents.get(i)), XContentType.JSON));
        }

        BulkResponse responses = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(responses.hasFailures());
        return !responses.hasFailures();
    }

    // 2、获取数据实现搜素功能
    public List<Map<String, Object>> queryDataByKeyWords(String keywords, int pageStart, int pageSize) throws IOException {
        // 针对分页进行业务处理
        if (pageStart < 1) {
            pageStart = 1;
        }
        // 条件查询
        SearchRequest searchRequest = new SearchRequest(Contant.JD_INDEX);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 分页
        searchSourceBuilder.from(pageStart);
        searchSourceBuilder.size(pageSize);
        // 精准匹配
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keywords);
        searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        // 执行搜索
        searchRequest.source(searchSourceBuilder);
        // 客户端查询操作
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        // 解析数据
        List<Map<String, Object>> dataList = new ArrayList<>();
        for (SearchHit documentFields : searchResponse.getHits().getHits()) {
            Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
            dataList.add(sourceAsMap);
        }
        return dataList;
    }


    // 3、获取数据实现高亮搜索搜素功能
    public List<Map<String, Object>> queryDataHighlightBuilder(String keywords, int pageStart, int pageSize) throws IOException {
        // 针对分页进行业务处理
        if (pageStart < 1) {
            pageStart = 1;
        }
        // 条件查询
        SearchRequest searchRequest = new SearchRequest(Contant.JD_INDEX);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 分页
        searchSourceBuilder.from(pageStart);
        searchSourceBuilder.size(pageSize);
        // 精准匹配
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keywords);
        searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        // 高亮搜索
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        // 多字段设置
        highlightBuilder.requireFieldMatch(false);
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);
        // 执行搜索
        searchRequest.source(searchSourceBuilder);
        // 客户端查询操作
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        // 解析数据
        List<Map<String, Object>> dataList = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            // 解析高亮字段
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField highlightField = highlightFields.get("title");
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            if (highlightField != null) {
                String newTitle = "";
                Text[] fragments = highlightField.getFragments();
                for (Text text : fragments) {
                    newTitle += text;
                }
                // 高亮字段替换原来字段
                sourceAsMap.put("title", newTitle);
            }

            dataList.add(sourceAsMap);

        }
        return dataList;
    }


}
